<template>
  <div class='container'>
    <el-dialog :visible="showDialog" @close="closeDialog">
    <div slot="title" style="color:white">{{ showTitle }}</div>
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item label="学科名称" class="is-required" prop="subjectName" label-width="100px">
        <el-input v-model="form.subjectName" autocomplete="off" placeholder="请输入学科名称"/>
      </el-form-item>
      <el-form-item label="是否显示" prop="isFrontDisplay" label-width="100px">
         <el-switch
        v-model="form.isFrontDisplay"
        active-color="#13ce66"
        inactive-color="#ff4949"
        :active-value=1
        :inactive-value=0 />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="handleClick">确 定</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    subInfo: {
      type: Object,
      default: null
    }
  },
  data () {
    return {
      form: {
        id: null,
        subjectName: '',
        isFrontDisplay: null
      },
      rules: {
        subjectName: [{ required: true, trigger: 'blur', message: '请输入学科名称' }]
      }
    }
  },
  computed: {
    showTitle () {
      return this.form.id ? '编辑学科' : '新增学科'
    }
  },
  watch: {
    showDialog (val) {
      if (val && this.subInfo.id) {
        this.form = this.subInfo
      }
    }
  },
  methods: {
    closeDialog () {
      this.form = {
        id: null,
        subjectName: '',
        isFrontDisplay: null
      }
      this.$refs.form.resetFields()
      this.$emit('update:showDialog', false)
    },
    async addSubject () {
      await add(this.form)
    },
    async updateSubject () {
      await update(this.form)
    },
    handleClick () {
      if (this.form.id) {
        this.updateSubject()
      } else {
        this.addSubject()
      }
      this.form = {
        id: null,
        subjectName: '',
        isFrontDisplay: null
      }
      this.$refs.form.resetFields()
      this.$emit('update:showDialog', false)
      this.$emit('fresh')
    }
  }
}
</script>

<style scoped lang='scss'>
  ::v-deep .el-dialog{
    width: 30%;
  }

</style>
